package org.sippr.controller;

import jakarta.validation.constraints.Pattern;
import org.sippr.pojo.Result;
import org.sippr.pojo.WordCls;
import org.sippr.service.WordClsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


//提示词分类服务
@RestController
@RequestMapping("/word/cls")
//字符串长度等合法性校验
public class WordClsController {
    @Autowired
    private WordClsService wordClsService;

    @PostMapping
    public Result<String> add(@Pattern(regexp = "^\\S{2,6}$") String name, @RequestParam(defaultValue = "-1") Integer parentId) {
        WordCls wc = wordClsService.findByName(name);
        if (wc == null) {
            wordClsService.add(name, parentId);
            return Result.success();
        } else {
            return Result.error("名字已被占用");
        }
    }

    //@RequestBody：一般用来处理请求体中的参数，Content-Type不等于 application/x-www-form-urlencoded
    //@RequestParam：一般用来处理请求头中的参数，用来处理Content-Type= application/x-www-form-urlencoded编码的内容
    @PutMapping
    public Result<String> update(@RequestBody @Validated(WordCls.Update.class) WordCls wordCls) {
        wordClsService.update(wordCls);
        return Result.success();
    }

    @DeleteMapping
    public Result<String> delete(Integer id) {
        wordClsService.delete(id);
        return Result.success();
    }

    @GetMapping
    public Result<List<WordCls>> list() {
        List<WordCls> list = wordClsService.list();
        return Result.success(list);
    }

    @GetMapping("childs")
    public Result getListByParentId(Integer parentId) {
        List<WordCls> list = wordClsService.getListByParentId(parentId);
        return Result.success(list);
    }

    @GetMapping("/tree")
    public Result tree() {
        List<WordCls> wordClss = wordClsService.list();
        if (wordClss.isEmpty()) {
            return Result.error("未获取到数据");
        }

        Map<Integer, WordCls> wordClsHashMap = new HashMap<>();
        for (WordCls item : wordClss) {
            wordClsHashMap.put(item.getId(), item);
        }

        List<WordCls> wordClsTree = new ArrayList<>();

        WordCls root = new WordCls();
        root.setId(-1);
        root.setName("根目录");
        wordClsTree.add(root);


        for (WordCls item : wordClss) {
            Integer parentId = item.getParentId();
            if (parentId == -1) {
                root.getChildren().add(item);
            } else {
                WordCls parent = wordClsHashMap.get(parentId);
                if (parent != null) {
                    parent.getChildren().add(item);
                }
            }
        }
        return Result.success(wordClsTree);
    }
}
